package com.ms.p2p.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.ms.common.bean.Message;
import com.ms.common.exception.NoticeException;
import com.ms.common.utils.*;

import com.ms.p2p.Constants;
import com.ms.p2p.provider.*;
import com.ms.p2p.service.RSAService;
import com.ms.p2p.plugin.validation.annotation.*;
import com.ms.p2p.bean.PageBean;
import com.ms.p2p.entity.account.YuEbao;
import com.ms.p2p.entity.loan.LoanCategory;
import com.ms.p2p.entity.member.Member;
import com.ms.p2p.utils.HttpRequestDeviceUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@Controller
public class IndexController extends BaseController {

	@Reference
	private YeahpaysProvider yeahpaysProvider;
	@Reference
	private MemberProvider memberProvider;
	@Reference
	private MemberAccountProvider memberAccountProvider;
	@Reference
	private LoanProvider loanProvider;
	@Reference
	private LoanTenderRecordProvider tenderService;
	@Reference
	private LoanCategoryProvider borrowTypeService;
	@Reference
	private SettingProvider settingProvider;
	@Reference
	private SendProvider smsService;
	@Autowired
	private RSAService rsaService;

	@Reference
	private LinkProvider linkProvider;

	@Reference
	private ArticleCategoryProvider categoryProvider;

	@Reference
	private ArticleProvider articleProvider;



	@Reference
	private RedPacketCategoryProvider redPacketCategoryProvider;

	@Reference
	private TestProvider testProvider;






	/**
	 * 首页
	 */
	@RequestMapping({"/index","/toIndex"})
	public String index(Model model,HttpServletRequest request) throws ParseException {

		if(HttpRequestDeviceUtils.isMobileDevice(request)){

			return "redirect:wap/toIndex";
		}


		//标
		PageBean borrowPage = new PageBean();
		borrowPage.setPageSize(6);
		List<Map<String,Object>> borrows = new ArrayList<>();
		borrows.addAll(loanProvider.findPager(null,null,null, null, null, null,
				null, null, null, null, null, null,null,null, borrowPage));

		model.addAttribute("borrows", borrows);
		//项目类型
		List<LoanCategory> types = borrowTypeService.findAll();
		model.addAttribute("types", types);
		//统计
		model.addAttribute("rookie", loanProvider.findRookie());
		model.addAttribute("links", linkProvider.getList());
		model.addAttribute("registerCount", memberProvider.countAllUser());
		model.addAttribute("tenderCount", memberProvider.countAllUserTender());
		model.addAttribute("dueInAmount",tenderService.countWailtAccount());
		model.addAttribute("totalTurnover", loanProvider.totalMoney());
		model.addAttribute("safeDate", MsDateUtils.getDate());
		//投资排行
		List<Map<String, Object>> ranks = memberAccountProvider.findtenderListIndex();
		model.addAttribute("ranks", ranks);
		return "/customer/index";
	}

	/**
	 * 首页
	 */
	@RequestMapping({"/current"})
	public String current(Model model)  {
		model.addAttribute("sum",memberAccountProvider.sumYuebao());
		model.addAttribute("scale",(memberAccountProvider.sumYuebao().doubleValue()/1000000D*100));
		return "/customer/current";
	}

	/**
	 * 注册
	 */
	@Validations(requiredStrings = {

			@RequiredStringValidator(fieldName = "mobile", message = "手机号码不能正确"),
			@RequiredStringValidator(fieldName = "pass1", message = "密码格式不正确"),
			@RequiredStringValidator(fieldName = "mobileCode", message = "手机验证码不能为空")
	})
	@RequestMapping("/regist")
	@ResponseBody
	public Message regist(String pass1,String mobile,String inviter,String mobileCode) {
		String username = mobile;
		String mobileCodeSession = (String) AppContext.getSessionAttr(Constants.REGIST_MOBILE_CODE_SESSION_KEY);
		if (StringUtils.isBlank(mobileCodeSession) || !mobileCodeSession.contains("_")) {
			throw new NoticeException("验证码错误或过期无效");
		}

		//验证码验证
		String[] codes = StringUtils.split(mobileCodeSession, "_");
		if(codes == null || codes.length != 2
				|| System.currentTimeMillis() - Long.valueOf(codes[1]) > 1000*60*10
				|| StringUtils.isBlank(codes[0]) || !StringUtils.equals(codes[0], mobileCode) ){
			throw new NoticeException("验证码错误或过期无效");
		}

		if (pass1.equals(username)) {
			throw new NoticeException("用户名与密码不能相同！");
		}

		if (!(mobile.matches("^1[0-9]{10}$"))) {
			throw new NoticeException("请输入正确的手机号码！");
		}

		if(!username.matches("^[a-zA-z][a-zA-Z0-9_]{3,18}$")){
			throw new NoticeException("用户名长度4-18位，字母、数字、下划线组合，必须以字母开头！");
		}

		String pwdRegex = "^(.*){6,20}$";
		if (!pass1.matches(pwdRegex)) {
			return Message.error("密码必须6-20位");
		}

		if (memberProvider.findByUserName(username) != null) {
			throw new NoticeException("该用户名已注册！");
		}

		if (memberProvider.findByMobilePhone(mobile) != null) {
			throw new NoticeException("该手机号码已注册！");
		}

		Member member = new Member();
		if (inviter != null && !inviter.equals("")) {
			Member remmendUser = memberProvider.findByMobilePhone(inviter);
			if (remmendUser == null) {
				throw new NoticeException("推荐人手机号码不存在");
			}
			member.setLevel(remmendUser.getLevel() + 1);
			member.setFirst_recommend_id(remmendUser.getFirst_recommend_id() == 0 ? remmendUser.getId() : remmendUser.getFirst_recommend_id());
			member.setRecommend_id(remmendUser.getId());
		} else {
			member.setLevel(0);
			member.setFirst_recommend_id(0);
		}
		// 插入注册用户
		member.setUser_name(username.trim());
		member.setMember_phone(mobile);
		member.setLogin_password(DigestUtils.md5Hex(pass1));
		member.setPayment_password(DigestUtils.md5Hex(pass1));
		member.setStatus(0);
		member.setLogin_times(1);
		member.setAdd_ip(AppContext.getRemoteIp());
		member.setAdd_time(MsDateUtils.getTime());
		member.setUp_ip(member.getAdd_ip());
		member.setUp_time(member.getAdd_time());
		member.setLast_ip(member.getAdd_ip());
		member.setLast_time(member.getAdd_time());
		member = memberProvider.register(member);
		AppContext.setSessionAttr(Constants.PRINCIPAL_SESSION_NAME, member);
		AppContext.removeAttribute(Constants.REGIST_MOBILE_CODE_SESSION_KEY);
		//使用

		return Message.success("注册成功");
	}

	/**
	 * 登录
	 */
	@RequestMapping({ "/member/common/login" })
	public String login() {
		if(getCurrentUser() != null){
			return "redirect:toIndex";
		}
		return "/customer/login";
	}

	/**
	 * 注册
	 * */
	@RequestMapping({ "/member/common/register" })
	public String register(String mobilePhone, Model model) {
		if (StringUtils.isNotBlank(mobilePhone)) {
			try {
				mobilePhone = new String(Base64Utils.decodeFromString(mobilePhone), "utf-8");
				Member user = memberProvider.findByMobilePhone(mobilePhone);
				if (user != null) {
					model.addAttribute("mobilePhone", user.getMember_phone());
				}
			} catch (Exception e) {
				logger.error("注册邀请手机转码失败", e);
			}
		}

		return "/customer/register";
	}

	@RequestMapping({ "/member/common/register2" })
	public String register2(HttpServletRequest request) {
		Member member = getCurrentUser();
		request.setAttribute("phone",member.getMember_phone());
		return "/customer/register_step2";
	}


	@RequestMapping({ "/register_confirm" })
	@ResponseBody
	public Message register_confirm(HttpServletRequest request, String mobileCode) {

		String mobileCodeSession = (String) AppContext.getSessionAttr(Constants.REGIST_MOBILE_CODE_SESSION_KEY);
		if (StringUtils.isBlank(mobileCodeSession) || !mobileCodeSession.contains("_")) {
			throw new NoticeException("验证码错误或过期无效");
		}

		//验证码验证
		String[] codes = StringUtils.split(mobileCodeSession, "_");
		if(codes == null || codes.length != 2 || System.currentTimeMillis() - Long.valueOf(codes[1]) > 1000*60*10 || StringUtils.isBlank(codes[0]) || !StringUtils.equals(codes[0], mobileCode) ){
			throw new NoticeException("验证码错误或过期无效");
		}
		Member user = getCurrentUser();
		user = memberProvider.findById(user.getId());
		user.setStatus(1);
		memberProvider.update(user);
		AppContext.setSessionAttr(Constants.PRINCIPAL_SESSION_NAME,user);
		return Message.success("验证成功");
	}

	/**
	 * 注册时获取验证码
	 */
	@RequestMapping("/step_2_regcode")
	@ResponseBody
	public String step_2_regcode( String mobile, String captcha, HttpServletResponse response) throws IOException, TemplateException {
		//发送校验

		Member user = memberProvider.findByMobilePhone(mobile);


		if (user != null&&!user.getUser_name().equals(getCurrentUser().getUser_name())) {
			return ResponseUtils.renderJSON(Message.error("手机号码已注册！"), response);
		}
		if(user==null){
			return ResponseUtils.renderJSON(Message.error("系统错误"), response);
		}

		if(user.getStatus()==1){
			return ResponseUtils.renderJSON(Message.error("用户已注册"), response);
		}
		//
		FreeMarkerConfigurer freeMarkerConfigurer = SpringContextHolder.getBean("freeMarkerConfigurer");
		String mobileCode = CommonUtil.getRandomNum(6);
		String nickname = settingProvider.findByCode("email_from_name")
				.getText();
		String templatePath = Constants.TEMPLATE_SMS_BIND;
		Configuration configuration = freeMarkerConfigurer.getConfiguration();
		Template template = configuration.getTemplate(templatePath, "utf-8");
		HashMap map = new HashMap();
		map.put("code",mobileCode);
		String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
		// 发送短信
		smsService.sendSMS(mobile,"【"+nickname+"】"+content, "注册", 0);
		AppContext.setSessionAttr(Constants.REGIST_MOBILE_CODE_SESSION_KEY, mobileCode + "_" + System.currentTimeMillis());
		return ResponseUtils.renderJSON(Message.success("发送成功"), response);
	}

	/**
	 * 注册
	 */
	@Validations(requiredStrings = {

			@RequiredStringValidator(fieldName = "mobile", message = "手机号码不能正确"),
			@RequiredStringValidator(fieldName = "pass1", message = "密码格式不正确")
	})
	@RequestMapping("/regist_step1")
	@ResponseBody
	public Message regist_step1(String pass1,String mobile,String inviter) {

		String username = mobile;
		if (pass1.equals(username)) {
			throw new NoticeException("用户名与密码不能相同！");
		}

		if (!(mobile.matches("^1[0-9]{10}$"))) {
			throw new NoticeException("请输入正确的手机号码！");
		}

		String pwdRegex = "^(.*){6,20}$";
		if (!pass1.matches(pwdRegex)) {
			return Message.error("密码必须6-20位");
		}

		if (memberProvider.findByUserName(username) != null) {
			throw new NoticeException("该用户名已注册！");
		}

		if (memberProvider.findByMobilePhone(mobile) != null) {
			throw new NoticeException("该手机号码已注册！");
		}

		Member member = new Member();
		if (inviter != null && !inviter.equals("")) {
			Member remmendUser = memberProvider.findByMobilePhone(inviter);
			if (remmendUser == null) {
				throw new NoticeException("推荐人手机号码不存在");
			}
			member.setLevel(remmendUser.getLevel() + 1);
			member.setFirst_recommend_id(remmendUser.getFirst_recommend_id() == 0 ? remmendUser.getId() : remmendUser.getFirst_recommend_id());
			member.setRecommend_id(remmendUser.getId());
		} else {
			member.setLevel(0);
			member.setFirst_recommend_id(0);
		}
		// 插入注册用户
		member.setUser_name(username.trim());
		member.setMember_phone(mobile);
		member.setLogin_password(DigestUtils.md5Hex(pass1));
		member.setPayment_password(DigestUtils.md5Hex(pass1));
		member.setStatus(0);
		member.setLogin_times(1);
		member.setAdd_ip(AppContext.getRemoteIp());
		member.setAdd_time(MsDateUtils.getTime());
		member.setUp_ip(member.getAdd_ip());
		member.setUp_time(member.getAdd_time());
		member.setLast_ip(member.getAdd_ip());
		member.setLast_time(member.getAdd_time());
		member = memberProvider.register(member);
		AppContext.setSessionAttr(Constants.PRINCIPAL_SESSION_NAME, member);
		AppContext.removeAttribute(Constants.REGIST_MOBILE_CODE_SESSION_KEY);
		return Message.success("注册成功");
	}



	@RequestMapping("/loginVerify")
	@ResponseBody


	@Validations(requiredStrings = {
			@RequiredStringValidator(fieldName = "username", message = "用户名不能为空"),
			@RequiredStringValidator(fieldName = "password", message = "密码不能为空"),

	})
	public Message login(String username, String password, String captcha,
						 HttpServletRequest request, HttpSession session) {


			password = rsaService.decryptParameter(password);
			rsaService.removePrivateKey(request);


		if(StringUtils.isBlank(password)){
			return Message.error("您的用户名或密码错误！");
		}


		Member user = memberProvider.findByUserNameOrMobilePhoneOrEmail(username.trim());


		if (user == null) {
			return Message.error("您的用户名或密码错误！");
		}



		if (!StringUtils.equals(user.getLogin_password(), DigestUtils.md5Hex(password))) {
			return Message.error("您的用户名或密码错误！");
		}


		session.setAttribute(Constants.PRINCIPAL_SESSION_NAME, user);
		user.setLast_ip(AppContext.getRemoteIp());
		user.setLast_time(MsDateUtils.getTime());
		user.setLogin_times(user.getLogin_times() + 1);
		memberProvider.updateById(user);
		return Message.success("登录成功");
	}



	/**
	 * 找回密码 第一步填写手机号验证码
	 */
	@RequestMapping(value = "/forget", method = RequestMethod.GET)
	public String toForget() {
		return "/customer/forget/step1";
	}


	/**
	 * 找回密码 校验手机号和验证码
	 */

	@RequestMapping(value = "/forget", method = RequestMethod.POST)
	public String forget1(String mobile, String captcha, HttpServletResponse response){

		if(StringUtils.isBlank(mobile)){
			return ResponseUtils.renderJSON(Message.error("手机号不能为空！"), response);
		}
		if(StringUtils.isBlank(captcha)){
			return ResponseUtils.renderJSON(Message.error("图形验证码不能为空！"), response);
		}
		mobile = mobile.trim();
		if(!Pattern.matches("^(13\\d|145|147|15[0-3]|15[5-9]|177|18[0-3]|18[5-9])\\d{8}$", mobile)){
			return ResponseUtils.renderJSON(Message.error("请填写正确的手机号码！"), response);
		}

		//验证码校验
		String code = (String) AppContext.getSessionAttr(Constants.CAPTCHA_SESSION_KEY);
		if (StringUtils.isBlank(code) || StringUtils.isBlank(captcha) || !code.toLowerCase().equals(captcha.toLowerCase())) {
			return ResponseUtils.renderJSON(Message.error("图形验证错误或已过期失效！"), response);
		}
		Member user = memberProvider.findByMobilePhone(mobile);
		if (user == null) {
			return ResponseUtils.renderJSON(Message.error("该手机绑定用户不存在"), response);
		}
		String token = CommonUtil.getUUID();
		AppContext.setSessionAttr(Constants.FORGET_PASS_SESSION_KEY, token);
		AppContext.setSessionAttr(token, mobile);
		return ResponseUtils.renderJSON(Message.success(token), response);
	}
	@RequestMapping(value = "/forget2", method = RequestMethod.GET)
	public String forgetSetp2(String token, Model model){
		String sessionToken = (String) AppContext.getSessionAttr(Constants.FORGET_PASS_SESSION_KEY);
		if (StringUtils.isBlank(sessionToken) || !token.equals(sessionToken)) {
			return "redirect:/forget";
		}
		String mobile = (String) AppContext.getSessionAttr(token);
		if (StringUtils.isBlank(mobile)) {
			return "redirect:/forget";
		}
		model.addAttribute("mobile", mobile);
		model.addAttribute("token", token);
		AppContext.setSessionAttr(Constants.FORGET_PASS_SESSION_KEY, token);
		AppContext.setSessionAttr(token, mobile);
		return "/customer/forget/step2";
	}

	/**
	 *	找回密码第二步--发送短信
	 */

	@RequestMapping(value = "/sms/forget", method = RequestMethod.POST)
	@ResponseBody
	public String SendSmsForget(String token, String captcha,
								HttpServletResponse response) throws IOException, TemplateException {

		if(StringUtils.isBlank(token)){
			return ResponseUtils.renderJSON(Message.error("请刷新页面，重新提交！"), response);
		}

		if(StringUtils.isBlank(captcha)){
			return ResponseUtils.renderJSON(Message.error("图形验证码不能为空！"), response);
		}

		String mobile = (String) AppContext.getSessionAttr(token);
		if (StringUtils.isBlank(mobile)) {
			return ResponseUtils.renderJSON(Message.error("请刷新页面，重新提交！"), response);
		}

		//发送校验
		String msg = isValidSms(mobile, captcha, true);
		if(StringUtils.isNotBlank(msg)){
			return ResponseUtils.renderJSON(Message.error(msg), response);
		}

		Member user = memberProvider.findByMobilePhone(mobile);
		if (user == null) {
			return ResponseUtils.renderJSON(Message.error("该手机绑定用户不存在"), response);
		}
		FreeMarkerConfigurer freeMarkerConfigurer = SpringContextHolder.getBean("freeMarkerConfigurer");

		String mobileCode = CommonUtil.getRandomNum(6);
		String nickname = settingProvider.findByCode("email_from_name")
				.getText();
		String templatePath = Constants.TEMPLATE_SMS_BIND;
		Configuration configuration = freeMarkerConfigurer.getConfiguration();
		Template template = configuration.getTemplate(templatePath, "utf-8");
		HashMap map = new HashMap();
		map.put("code",mobileCode);
		String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
		// 发送短信
		Message message = smsService.sendSMS(mobile,"【"+nickname+"】"+content, "注册", 0);

		if (Message.Type.success.equals(message.getType())) {
			AppContext.setSessionAttr(Constants.COMMON_MOBILE_CODE_SESSION_KEY, mobileCode + "_" + System.currentTimeMillis());
			AppContext.setSessionAttr(Constants.FORGET_PASS_SESSION_KEY + mobile, user.getId() + "");
		}

		return ResponseUtils.renderJSON(message, response);
	}

	/**
	 *	找回密码第二步--验证短信验证码
	 */
	@RequestMapping(value = "/forget2", method = RequestMethod.POST)
	@ResponseBody
	public String forget(String token, String captcha, String code, HttpServletResponse response) {

		//验证码校验
		String sessionCaptcha = (String) AppContext.getSessionAttr(Constants.CAPTCHA_SESSION_KEY);
		if (StringUtils.isBlank(sessionCaptcha) || StringUtils.isBlank(captcha) || !sessionCaptcha.toLowerCase().equals(captcha.toLowerCase())) {
			return ResponseUtils.renderJSON(Message.error("图形验证码不能为空"), response);
		}

		String sessionToken = (String) AppContext.getSessionAttr(Constants.FORGET_PASS_SESSION_KEY);
		if (StringUtils.isBlank(sessionToken) || StringUtils.isBlank(token) || !token.equals(sessionToken)) {
			return ResponseUtils.renderJSON(Message.error("请刷新页面，重新提交！"), response);
		}

		//获取手机号码
		String mobile = (String) AppContext.getSessionAttr(token);
		if(StringUtils.isBlank(mobile)){
			return ResponseUtils.renderJSON(Message.error("请刷新页面，重新提交！"), response);
		}

		//短信验证码校验
		String mobileCode = (String) AppContext.getSessionAttr(Constants.COMMON_MOBILE_CODE_SESSION_KEY);
		String userid = (String) AppContext.getSessionAttr(Constants.FORGET_PASS_SESSION_KEY + mobile);
		if(StringUtils.isBlank(mobileCode) && StringUtils.isBlank(userid)){
			return ResponseUtils.renderJSON(Message.error("请发送短信验证码！"), response);
		}

		if(StringUtils.isBlank(userid)){
			return ResponseUtils.renderJSON(Message.error("请刷新页面，重新提交！"), response);
		}

		if (StringUtils.isBlank(mobileCode) || StringUtils.isBlank(code) || !mobileCode.contains("_")) {
			return ResponseUtils.renderJSON(Message.error("短信验证码错误或已过期失效！"), response);
		}

		String[] codes = StringUtils.split(mobileCode, "_");
		if(codes == null || codes.length != 2 || System.currentTimeMillis() - Long.valueOf(codes[1]) > 1000*60*10){
			return ResponseUtils.renderJSON(Message.error("短信验证码错误或已过期失效！"), response);
		}
		//
		token = CommonUtil.getUUID();
		AppContext.setSessionAttr(Constants.FORGET_PASS_SESSION_KEY, token);
		AppContext.setSessionAttr(token + "_USERID", userid);
		//
		AppContext.removeAttribute(Constants.FORGET_PASS_SESSION_KEY + mobile);
		AppContext.removeAttribute(Constants.COMMON_MOBILE_CODE_SESSION_KEY);
		AppContext.removeAttribute(token);

		return ResponseUtils.renderJSON(Message.success(token), response);
	}


	@RequestMapping(value = "/forget3", method = RequestMethod.GET)
	public String forget3(String token, Model model){
		String sessionToken = (String) AppContext.getSessionAttr(Constants.FORGET_PASS_SESSION_KEY);
		if (StringUtils.isBlank(sessionToken) || !token.equals(sessionToken)) {
			return "redirect:/forget";
		}
		String userId = (String) AppContext.getSessionAttr(sessionToken + "_USERID");
		if (StringUtils.isBlank(userId)) {
			return "redirect:/forget";
		}
		model.addAttribute("token", token);
		AppContext.setSessionAttr(Constants.FORGET_PASS_SESSION_KEY, token);
		AppContext.setSessionAttr(token + "_USERID", userId);
		return "/customer/forget/step3";
	}

	/**
	 * 重置密码
	 */
	@RequestMapping(value = "/forget3", method = RequestMethod.POST)
	@ResponseBody
	public String forgetResetPwd(String token, String pwd, HttpServletResponse response){

		String sessionToken = (String) AppContext.getSessionAttr(Constants.FORGET_PASS_SESSION_KEY);
		if (StringUtils.isBlank(sessionToken) || StringUtils.isBlank(token) || !sessionToken.toLowerCase().equals(token.toLowerCase())) {
			return ResponseUtils.renderJSON(Message.error("请刷新页面,重新提交！"), response);
		}

		String userId = (String) AppContext.getSessionAttr(token + "_USERID");
		if (StringUtils.isBlank(userId)) {
			return ResponseUtils.renderJSON(Message.error("请刷新页面,重新提交！"), response);
		}

		Member user = memberProvider.findById(Integer.valueOf(userId));
		if (user == null) {
			return ResponseUtils.renderJSON(Message.error("该手机绑定用户不存在"), response);
		}

		user.setLogin_password(DigestUtils.md5Hex(pwd));
		memberProvider.update(user);

		token = CommonUtil.getUUID();
		AppContext.setSessionAttr(Constants.FORGET_PASS_SESSION_KEY + "_SUCCESS", token);
		//
		AppContext.removeAttribute(Constants.FORGET_PASS_SESSION_KEY);
		AppContext.removeAttribute(token + "_USERID");

		return ResponseUtils.renderJSON(Message.success(token), response);
	}

	@RequestMapping(value = "/forget4", method = RequestMethod.GET)
	public String forget4(String token){
		String sessionToken = (String) AppContext.getSessionAttr(Constants.FORGET_PASS_SESSION_KEY + "_SUCCESS");
		if (StringUtils.isBlank(sessionToken) || !token.equals(sessionToken)) {
			return "redirect:/forget";
		}
		AppContext.removeAttribute(Constants.FORGET_PASS_SESSION_KEY + "_SUCCESS");
		return "/customer/forget/step4";
	}




	/**
	 * 注册时获取验证码
	 */
	@RequestMapping("/regcode")
	@ResponseBody
	public String regcode( String mobile, String captcha, HttpServletResponse response) throws IOException, TemplateException {
		//发送校验
		String msg = isValidSms(mobile, captcha, true);
		if(StringUtils.isNotBlank(msg)){
			return ResponseUtils.renderJSON(Message.error(msg), response);
		}
		Member user = memberProvider.findByMobilePhone(mobile);
		if (user != null) {
			return ResponseUtils.renderJSON(Message.error("手机号码已注册！"), response);
		}
		//
		FreeMarkerConfigurer freeMarkerConfigurer = SpringContextHolder.getBean("freeMarkerConfigurer");
		String mobileCode = CommonUtil.getRandomNum(6);
		String nickname = settingProvider.findByCode("email_from_name")
				.getText();
		String templatePath = Constants.TEMPLATE_SMS_BIND;
		Configuration configuration = freeMarkerConfigurer.getConfiguration();
		Template template = configuration.getTemplate(templatePath, "utf-8");
		HashMap map = new HashMap();
		map.put("code",mobileCode);
		String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
		// 发送短信
		Message message = smsService.sendSMS(mobile,"【"+nickname+"】"+content, "注册", 0);

		if (Message.Type.success.equals(message.getType())) {
			AppContext.setSessionAttr(Constants.REGIST_MOBILE_CODE_SESSION_KEY, mobileCode + "_" + System.currentTimeMillis());
		}

		return ResponseUtils.renderJSON(message, response);
	}




	/**
	 * 退出
	 */
	@RequestMapping("/logout")
	public String logout(){
		AppContext.removeAttribute(Constants.PRINCIPAL_SESSION_NAME);
		return "redirect:index";
	}

}
